package pers.kw.config.feign;

import com.alibaba.fastjson.JSON;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pers.kw.config.BeanConfig;
import pers.kw.config.LoginConfig;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Configuration
public class FeignAuthApiConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("token信息传递...");
        Map<String, String> headers = getHeaders(getHttpServletRequest());
        LoginConfig loginConfig = BeanConfig.getBean(LoginConfig.class);
        log.info("token信息传递... config:{}", JSON.toJSONString(loginConfig));
        headers.put("Authorization", loginConfig.getAuthorization());
        for (String headerName : headers.keySet()) {
            if ("Authorization".equalsIgnoreCase(headerName)) {
                requestTemplate.header(headerName, loginConfig.getAuthorization());
            }
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            log.error("异常信息:", e);
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>(5);
        try {
            Enumeration<String> enumeration = request.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        } catch (Exception e) {
            log.error("透传解析异常", e);
        }
        return map;
    }

}
